package cn.xinfei.xdecision.common.service.rpc;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
@Component
public class RpcContextRequestInterceptor implements RequestInterceptor {

    @Value("${spring.application.name}")
    private String appName;

    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void apply(RequestTemplate template) {
        RpcContext rpcContext = RpcContext.getCurrentContext();
        if (rpcContext == null) {
            return;
        }
        try {
            fillRequester(rpcContext);
            template.header("Rpc-Context", mapper.writeValueAsString(rpcContext));
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Rpc context is invalid.", e);
        }
    }

    private void fillRequester(RpcContext rpcContext) {
        String hostName = "";
        try {
            InetAddress ia = InetAddress.getLocalHost();
            if (ia != null) {
                hostName = ia.getHostName();
            }
        } catch (UnknownHostException e) {
            log.error("",e);
        }

        StringBuilder sb = new StringBuilder()
                .append("[")
                .append(appName)
                .append("].[")
                .append(hostName)
                .append("]");
        rpcContext.put("requester", sb.toString());
    }

}